package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import model.MappedContext;
import model.MappedHost;
import model.MappedWrapper;
import model.Mapper;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {


    /**
     * webapps的绝对路径
     */
    private String webapps = "";

    /**
     * http://localhost:8080,根据server中的配置组装域名+端口号
     */
    private String hostName = "";

    /**
     * 定义socket监听的端口号,从server.xml中获取
     */
    private int port;

    /**
     * 该mapper用来保存子容器MappedHost,MapperContext,MapperWrapper等信息
     */
    private Mapper mapper = new Mapper();


    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {

        //加载解析server.xml的相关配置,获取host,port,以及webapps的绝对路径
        loadServer();
        // 加载解析相关的配置，web.xml，并将servlet,context等数据保存到mapper变量中
        loadServlet();
        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);
        while(true) {
            Socket socket = serverSocket.accept();
            // 处理request请求
            RequestProcessor requestProcessor = new RequestProcessor(socket,mapper);
            threadPoolExecutor.execute(requestProcessor);
        }
    }

    /**
     * 加载解析server.xml,获取host,port,以及webapps的绝对路径
     */
    private void loadServer() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();
            List<Element> selectNodes = rootElement.selectNodes("//Service");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element = selectNodes.get(i);
                // <Connector port="8080"/>
                Element portElement = (Element) element.selectSingleNode("Connector");
                // 获取监听接口
                port = Integer.parseInt(portElement.attributeValue("port"));
                //<Engine>
                //    <MappedHost name="localhost" appBase="‎/User/xuyaxi/software/webapps">
                //     </MappedHost>
                //</Engine>, 获取host以及webapps的路径
                Element engineElement = (Element) element.selectSingleNode("Engine");
                List<Element> hostList = engineElement.selectNodes("Host");
                for (int j = 0; j < hostList.size(); j++) {
                    Element element1 = (Element) hostList.get(j);
                    // 组装http://localhost:8080路径
                    hostName = element1.attributeValue("name") + ":" +port;
                    // webapps的绝对路径
                    webapps = element1.attributeValue("appBase");
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }
    /**
     * 加载解析相关的配置，web.xml，并将servlet,context等数据保存到mapper变量中
     */
    private void loadServlet() throws FileNotFoundException {
        //遍历所有webapps下的所有的web.xml
        File file = new File(webapps);
        File[] files = file.listFiles();
        MappedHost mappedHost = new MappedHost(hostName,null);
        List<MappedContext> mappedContexts = new ArrayList<>();
        for (int j = 0; j < files.length; j++) {
            File file1 = files[j];
            String path = file1.getPath();
            List<MappedWrapper> mappedWrappers = new ArrayList<>();
            // 将webapps下所有的项目web.xml文件读到输入流以获取servlet的配置信息
            System.out.println("------"+path);
            InputStream resourceAsStream = new FileInputStream(path + "/web.xml");
            SAXReader saxReader = new SAXReader();
            try {
                Document document = saxReader.read(resourceAsStream);
                Element rootElement = document.getRootElement();
                List<Element> selectNodes = rootElement.selectNodes("//servlet");
                for (int i = 0; i < selectNodes.size(); i++) {
                    Element element =  selectNodes.get(i);
                    // <servlet-name>lagou</servlet-name>
                    Element servletNameElement = (Element) element.selectSingleNode("servlet-name");
                    String servletName = servletNameElement.getStringValue();
                    // <servlet-class>server.LagouServlet</servlet-class>
                    Element servletClassElement = (Element) element.selectSingleNode("servlet-class");
                    String servletClass = servletClassElement.getStringValue();
                    URLClassLoader loader = null;
                    try {
                        // create a URLClassLoader
                        URL[] urls = new URL[1];
                        URLStreamHandler streamHandler = null;
                        File classPath = new File(path);
                        //类加载器加载路径
                        String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString() ;
                        urls[0] = new URL(null, repository, streamHandler);
                        loader = new URLClassLoader(urls);
                    }
                    catch (IOException e) {
                        throw new IllegalStateException(e);
                    }
                    Class clazz = null;
                    try {
                        //加载Servlet类
                        clazz = loader.loadClass(servletClass);
                    }
                    catch (ClassNotFoundException e) {
                        throw new IllegalStateException(e);
                    }
                    // 根据servlet-name的值找到url-pattern
                    Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                    // /lagou
                    String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                    urlPattern = urlPattern.substring(urlPattern.lastIndexOf("/"));
                    // 将每个servlet实例保存到MapperWrapper对象中
                    MappedWrapper mappedWrapper = new MappedWrapper(urlPattern,(HttpServlet) clazz.newInstance());
                    mappedWrappers.add(mappedWrapper);
                }
                // 将所有的MappedWrapper保存到对应的context实例中
                MappedContext mappedContext = new MappedContext(path.substring(path.lastIndexOf("/")),null,mappedWrappers);
                mappedContexts.add(mappedContext);
            } catch (DocumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }
        mappedHost.setMappedContexts(mappedContexts);
        mapper.setMappedHost(mappedHost);
    }
    /**
     * Minicat 的程序启动入口
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
